/**
 * 
 */
package za.co.sindi.oauth.core.result.http;

import java.io.IOException;
import java.util.Map.Entry;

import za.co.sindi.oauth.core.context.ApplicationContext;
import za.co.sindi.oauth.core.context.HttpRequestContext;
import za.co.sindi.oauth.core.context.HttpResponseContext;
import za.co.sindi.oauth.core.result.message.Message;
import za.co.sindi.oauth.exception.ResultException;

/**
 * @author Buhake Sindi
 * @since 07 May 2012
 *
 */
public class HttpResultMessage extends AbstractHttpResult {

	private int statusCode;
	private Message message;
	
	/**
	 * @param message
	 */
	public HttpResultMessage(int statusCode, Message message) {
		super();
		if (message == null) {
			throw new IllegalArgumentException("A message may not be null.");
		}
		
		this.statusCode = statusCode;
		this.message = message;
	}

	/* (non-Javadoc)
	 * @see com.neurologic.oauth.core.result.Result#executeResult(com.neurologic.oauth.core.context.ApplicationContext)
	 */
	@Override
	public void executeResult(ApplicationContext applicationContext) throws ResultException {
		// TODO Auto-generated method stub
		if (applicationContext == null) {
			throw new IllegalArgumentException("ApplicationContext may not be null.");
		}
		
		executeResult((HttpRequestContext)applicationContext.getRequestContext(), (HttpResponseContext)applicationContext.getResponseContext());
	}
	
	protected void executeResult(HttpRequestContext requestContext, HttpResponseContext responseContext) throws ResultException {
		try {
			if (statusCode < 100) {
				throw new IOException("Invalid HTTP Status Code '" + statusCode + "'.");
			}

			for (Entry<String, String> entry : headersEntrySet()) {
				responseContext.addHeader(entry.getKey(), entry.getValue());
			}

			// Set status
			responseContext.setStatusCode(statusCode);

			if (message != null) {
				// Set Content-Type
				responseContext.addHeader("Content-Type", message.getContentType());
				// Set Content-Length
				responseContext.addHeader("Content-Length", String.valueOf(message.getContentLength()));

				// Write...
				message.writeTo(responseContext.getOutputStream());
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new ResultException(e.getLocalizedMessage(), e);
		}
	}
}
